

//
//  LYJobHuntingController.m
//  SelectCity
//
//  Created by liuyan on 2019/3/29.
//  Copyright © 2019年 liuyan. All rights reserved.
//

#import "LYJobHuntingController.h"
#import "LYResumePayTypeCell.h"
#import "LYResumeTopPriceCell.h"
#import "LYJobHuntingModel.h"
#import "LYResumePaytypeModel.h"
#import "LYResumetopView.h"

#import "LYCoinsRechargeViewController.h"
#import "InviteReexamineSelectJobViewController.h"

@interface LYJobHuntingController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) LYResumetopView *header;
@property (nonatomic, strong) UIButton *payBtn;

@property (nonatomic, assign) NSInteger jobIndex;

@property (nonatomic, assign) NSInteger coins;
@property (nonatomic, strong) NSDictionary *dataDic;

@property (nonatomic, strong) UILabel *coinsLabel;

@end

@implementation LYJobHuntingController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
     [self requestAmountData];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self createSubview];
}

- (void)createSubview{
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH,HEIGHT-HeightOfStatusBarAndNavigationBar) style:UITableViewStyleGrouped];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    self.tableview.showsVerticalScrollIndicator = NO;
    self.tableview.estimatedRowHeight = 0;
    self.tableview.estimatedSectionHeaderHeight = 0;
    self.tableview.estimatedSectionFooterHeight = 0;
    self.tableview.hidden = YES;
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableview.backgroundColor = RGB(247, 247, 247);
    self.tableview.sectionIndexBackgroundColor = [UIColor clearColor];
    
    [self.tableview registerClass:[LYResumeTopPriceCell class] forCellReuseIdentifier:kCellIdentifier_LYResumeTopPriceCell];
    [self.tableview registerClass:[LYResumePayTypeCell class] forCellReuseIdentifier:kCellIdentifier_LYResumePayTypeCell];
    [self.view addSubview:self.tableview];
    
    self.header = [[LYResumetopView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 70)];
    __weak typeof(self) weakSelf = self;
    self.header.block = ^(){
        [weakSelf jumpToSelectPositon];
    };
    self.tableview.tableHeaderView = self.header;
    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 150)];
    self.tableview.tableFooterView = footer;
    
    self.coinsLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 15, WIDTH - 20, 30)];
    [footer addSubview: self.coinsLabel];
    self.coinsLabel.textColor = RGB(85, 85, 85);
    self.coinsLabel.font = [UIFont systemFontOfSize:14];
    
    UIButton *paybutton = [UIButton buttonWithType:UIButtonTypeCustom];
    paybutton.frame = CGRectMake( 40, 80, WIDTH -80, 40);
    paybutton.layer.cornerRadius = paybutton.height/2;
    paybutton.clipsToBounds = YES;
    paybutton.backgroundColor = [UIColor orangeColor];
    [paybutton setTitle:@"立即支付" forState:UIControlStateNormal];
    [paybutton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.payBtn = paybutton;
    paybutton.titleLabel.font = [UIFont systemFontOfSize:14];
    [paybutton addTarget:self action:@selector(paybuttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [footer addSubview:paybutton];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *array = self.dataArray[section];
    return array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *array = self.dataArray[indexPath.section];
    LYResumeTopPriceCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_LYResumeTopPriceCell forIndexPath:indexPath];
    cell.jobmodel = array[indexPath.row];
    return cell;
}

#pragma mark -- UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *array = self.dataArray[indexPath.section];
        LYJobHuntingModel *model = array[indexPath.row];
        if (!model.isSelected) {
            for (LYJobHuntingModel *pricemodel in array) {
                if (model == pricemodel) {
                    pricemodel.isSelected = YES;
                    self.jobIndex = indexPath.row;
                    NSInteger status = [self.dataDic[@"status"] integerValue];
                    NSInteger repeat_order = [self.dataDic[@"repeat_order"] integerValue];
                    if (status == 0) {
                        //未开通
                        if (model.price > self.coins) {
                            //立即充值
                            [self.payBtn setTitle:@"立即充值" forState:UIControlStateNormal];
                        }else{
                            //立即支付
                            [self.payBtn setTitle:@"立即支付" forState:UIControlStateNormal];
                        }
                    }else{
                        //已开通
                        if (repeat_order == 1){
                            //支持重复购买
                            if (model.price > self.coins) {
                                //立即充值
                                [self.payBtn setTitle:@"立即充值" forState:UIControlStateNormal];
                            }else{
                                //立即支付
                                [self.payBtn setTitle:@"立即支付" forState:UIControlStateNormal];
                            }
                        }
                    }
                }else{
                    pricemodel.isSelected = NO;
                }
            }
            [tableView reloadData];
        }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 65.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0.001f;
    }
    return 8;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.001f;
}

#pragma mark-- LoadData
//请求余额
- (void)requestAmountData{
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    __weak typeof(self) weakSelf = self;
    [BaseNetManager requestWithMethod:POST path:Company_GetPayWallet_URL params:dic successBlock:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            //钱包信息
            weakSelf.coins = [responseObject[@"data"][@"coins"] floatValue];
            NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"我的账户聘豆数："];
            NSAttributedString *strq = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%li",weakSelf.coins] attributes:@{NSForegroundColorAttributeName :[UIColor redColor],NSFontAttributeName : [UIFont systemFontOfSize:15]}];
            [str appendAttributedString:strq];
            weakSelf.coinsLabel.attributedText = str;
            [weakSelf requestSeverInfoData];
        }else{
            SVPHUDError(responseObject[@"msg"]);
        }
    } failurBlock:^(NSError *error) {
        SVPHUDError(NetErrorAlertText);
    }];
}

//获取服务信息
- (void)requestSeverInfoData{
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    dic[@"service_alias"] = self.service_alias;
    [dic setObject:((self.job_id&&self.job_id.length)?self.job_id:@"") forKey:@"job_id"];
    __weak typeof(self) weakSelf = self;
    [BaseNetManager requestWithMethod:POST path:H5_getServiceInfo_URL params:dic successBlock:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            //获取服务信息
            weakSelf.tableview.hidden = NO;
            weakSelf.dataDic = responseObject[@"data"];
            [weakSelf organizeData:responseObject[@"data"]];
            [weakSelf.tableview reloadData];
        }else{
            SVPHUDError(responseObject[@"msg"]);
        }
    } failurBlock:^(NSError *error) {
        SVPHUDError(NetErrorAlertText);
    }];
}

- (void)organizeData:(NSDictionary *)dataDic{
    self.dataArray = [NSMutableArray array];
    self.title = dataDic[@"name"];
    [self.header setData:dataDic service_aliasType:self.service_alias jobName:self.job_name isHtml:self.isHtml];
    NSMutableArray *priceArray = [NSMutableArray array];
    NSArray *price = dataDic[@"setmeal"];
    NSInteger selectCount = 0;
    for (NSDictionary *dic in price) {
        LYJobHuntingModel *model = [LYJobHuntingModel mj_objectWithKeyValues:dic];
        model.setmeal_id = [dic[@"id"] integerValue];
        NSInteger currentindex = [self.setmeal_id integerValue];
        if (model.setmeal_id == currentindex) {
            model.isSelected = YES;
            self.jobIndex = [price indexOfObject:dic];
            selectCount ++;
        }else{
            model.isSelected = NO;
        }
        [priceArray addObject:model];
    }
    
    if (selectCount == 0 && priceArray.count) {
        self.jobIndex = 0;
        LYJobHuntingModel *model = priceArray[0];
        model.isSelected = YES;
    }
    
    NSInteger status = [dataDic[@"status"] integerValue];
    NSInteger repeat_order = [dataDic[@"repeat_order"] integerValue];
    LYJobHuntingModel *pricemodel = priceArray[self.jobIndex];
    NSInteger currentPrice = pricemodel.price;
    if (status == 0) {
        //未开通 支持购买
        self.payBtn.backgroundColor = [UIColor orangeColor];
        self.payBtn.userInteractionEnabled = YES;
        if (currentPrice > self.coins) {
            //大于余额
             [self.payBtn setTitle:@"立即充值" forState:UIControlStateNormal];
        }else{
            [self.payBtn setTitle:@"立即支付" forState:UIControlStateNormal];
        }
    }else{
        //已开通
        if (repeat_order == 1) {
            //支持购买
            self.payBtn.backgroundColor = [UIColor orangeColor];
            self.payBtn.userInteractionEnabled = YES;
            if (currentPrice > self.coins) {
                //大于余额
                [self.payBtn setTitle:@"立即充值" forState:UIControlStateNormal];
            }else{
                [self.payBtn setTitle:@"立即支付" forState:UIControlStateNormal];
            }
        }else{
            //不支持购买
            self.payBtn.backgroundColor = [UIColor lightGrayColor];
            self.payBtn.userInteractionEnabled = NO;
        }
    }
    [_dataArray addObject:priceArray];
    [self.tableview reloadData];
}



#pragma mark -- Action
- (void)jumpToSelectPositon{
    InviteReexamineSelectJobViewController *IRSJVC = [[InviteReexamineSelectJobViewController alloc] init];
    IRSJVC.dataArray = [NSMutableArray arrayWithCapacity:0];
    for (InterviewBaseinfoJobModel *model in self.jobArray) {
        [IRSJVC.dataArray addObject:[model copy]];
    }
    __weak __typeof(self)weakSelf = self;
    IRSJVC.select = ^(NSString * _Nullable jobId, NSString * _Nullable jobTitle, NSString * _Nullable wageCN) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        strongSelf.job_id = jobId;
        strongSelf.job_name = jobTitle;
        [strongSelf requestSeverInfoData];
    };
    [self.navigationController pushViewController:IRSJVC animated:YES];
}

- (void)paybuttonClick:(UIButton *)button{
    //价格
    NSArray *priceArray = self.dataArray[0];
    LYJobHuntingModel *pricemodel = priceArray[self.jobIndex];
    if ([button.titleLabel.text isEqualToString:@"立即充值"]) {
        //充值
        LYCoinsRechargeViewController *rechargeVC = [[LYCoinsRechargeViewController alloc] init];
        [self.navigationController pushViewController:rechargeVC animated:YES];
    }else{
        //购买
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
        dic = [UIToolsControl getPublicParameter];
        dic[@"service_alias"] = self.service_alias;
        dic[@"setmeal_id"] = [NSString stringWithFormat:@"%li", (long)pricemodel.setmeal_id];
        dic[@"payment"] = @"coins";
        dic[@"job_id"] = self.job_id;
        __weak typeof(self) weakSelf = self;
        [BaseNetManager requestWithMethod:POST path:H5_openService_URL params:dic successBlock:^(NSDictionary *responseObject) {
            if ([responseObject[@"code"] integerValue] == 2000) {
                if (self.showType == GeneralWebViewTypeOfCoach) {
                    CustomView *alertView = [[CustomView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"恭喜您，成功购买求职教练“%@”", pricemodel.name] prompt:@"请您将个人简历发送至btpin@sina.com 邮箱 专业顾问第一时间与您联系！" sureBtn:@"确认" cancleBtn:@"取消" size:200];
                    alertView.resultIndex = ^(NSInteger index){
                        //回调---处理一系列动作
                        [weakSelf.navigationController popToRootViewControllerAnimated:YES];
                    };
                    [alertView showXLAlertView];
                } else {
                    SVPHUDSuccess(@"支付成功");
                    [weakSelf.navigationController popToRootViewControllerAnimated:YES];
                }
            } else {
                SVPHUDError(responseObject[@"msg"]);
            }
        } failurBlock:^(NSError *error) {
            SVPHUDError(NetErrorAlertText);
        }];
    }
}

@end
